package com.codes.config.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.codes.config.token.TokenUtil;
import com.codes.core.common.result.ResultCode;
import com.codes.core.utils.UserUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//@Component
@Configuration
@Slf4j
public class MyInterceptor implements HandlerInterceptor {
    //在请求处理之前进行调用（Controller方法调用之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        log.info("MyInterceptor-preHandle被调用");
     //   Map map =(Map)httpServletRequest.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
        String paths = request.getServletPath();
        String urlString = request.getRequestURI();
        log.info(paths);

        if(urlString.endsWith("login.html")|| urlString.endsWith("login")){
            System.out.println("login 接口 不拦截");
            return true;
        }
        // 验证token

        String token = request.getHeader("token"); //获取请求传来的token
        if(null == token){
            // token 完毕

            HttpSession session = request.getSession();
            //这里的User是登陆时放入session的
            Map loginUser = UserUtil.getSessionUser(request);
            if(null != loginUser){
                return  true;
            }
            response.sendRedirect(request.getContextPath() +"/login.html");
           // response.sendRedirect( "/login.html"); // 记得这个重定向出的问题
            return  false;
        }
        // 校验 token
        Claims claims = TokenUtil.verifyJwt(token); //getClaims(token);
        if (claims == null) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = null ;
            JSONObject res = new JSONObject();
            res.put("success","false");
            res.put("msg","timeout");
            res.put("code", ResultCode.TIMEOUT.getCode());// 登录信息超时
            out = response.getWriter();
            out.append(res.toString());
            return  false;

        }else {
            return  true;
        }



//        List<String> list = (ArrayList) request.getSession().getAttribute("permission"); // 用户所有的资源
//        // 截取 请求的资源最后 URL
//        String endUrl =  urlString.substring(urlString.lastIndexOf("/")+1,urlString.length()) ;
//        if(null == null) {
//            // 标识 用户已登录
//            // 验证其资源 是否有权限访问
//            // 只拦截html  主页不拦截
//            if(urlString.endsWith("index.html")|| urlString.endsWith("main.html"))  return true;
//            if(urlString.endsWith("html")){
//                for (String  s : list){
//                    if(s.endsWith(endUrl)){  // 说明 用户有此权限，，可以访问
//                        return true;
//                    }else {
//                        // 没有访问权限，去404 吧
//                        response.sendRedirect("/page/404.html");
//                        return  false;
//                    }
//                }
//
//            }else {
//                return true;
//            }
//
//           return true;    //如果false，停止流程，api被拦截
//        }else {
//
//            response.sendRedirect("/login.html");
//            return  false;
//
//        }
    }
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
      //  System.out.println("postHandle被调用");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
       // System.out.println("afterCompletion被调用");
    }
}